<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { AxiosResponse } from "axios";
import { JxtechEditTable, useJxtechEditTable } from "@whjxtech/jxtech-component";
import { commonList } from "@/api/modules/org/code-list";
import { JxtechEditTableExtColumn } from "@/comp-ext/types";

type IJxtechEditTableProps = {
  showFooterAdd?: boolean;
  tableColumn: JxtechEditTableExtColumn[];
  data?: any[];
  /**加载数据方法 */
  loadData?: () => Promise<AxiosResponse<any[]>>;
};

const props = withDefaults(defineProps<IJxtechEditTableProps>(), {});

const JxtechEditTableRef = ref();

const { loadTable, getInputBean, addRowData } = useJxtechEditTable(JxtechEditTableRef);

function handleTableColumn(tableColumn: JxtechEditTableExtColumn[]) {
  tableColumn.forEach(column => {
    if (column.codeItemId) {
      column.loadOptionDataFunction = () => {
        return commonList(column.codeItemId || "");
      };
      column.optionLabelKey = "value";
      column.optionValueKey = "key";
    }
  });
  return tableColumn;
}

function handleTableSlot(tableColumn: JxtechEditTableExtColumn[]) {
  const slotArr: string[] = [];
  tableColumn.forEach(column => {
    if (column.slot) slotArr.push(column.slot);
  });
  return slotArr;
}

const EditTableExtState = reactive({
  data: props.data,
  tableColumn: handleTableColumn(props.tableColumn),
  slotNameArr: handleTableSlot(props.tableColumn)
});

watch(
  () => props.tableColumn,
  val => {
    EditTableExtState.tableColumn = [...handleTableColumn(val)];
    EditTableExtState.slotNameArr = [...handleTableSlot(val)];
  }
);

watch(
  () => props.data,
  val => {
    EditTableExtState.data = val;
  }
);

defineExpose({
  loadTable: () => loadTable(),
  getInputBean: () => getInputBean(),
  addRowData: (data?: any) => addRowData(data)
});
</script>
<template>
  <JxtechEditTable
    ref="JxtechEditTableRef"
    :show-footer-add="showFooterAdd"
    :table-column="tableColumn"
    :data="EditTableExtState.data"
    :load-data="loadData"
  >
    <template v-for="item in EditTableExtState.slotNameArr" #[item]="scope">
      <slot :name="item" :row="scope.row" :column="scope.column" :index="scope.index">
        {{ item }}
      </slot>
    </template>
  </JxtechEditTable>
</template>
